package lv.yasa.helper;

import android.app.Activity;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.widget.Toast;

public class SpeakHelper implements OnInitListener  {
	private static SpeakHelper instance = null;
	
	public static SpeakHelper getInstance()
	{
		return instance;
	}

	private static int MY_DATA_CHECK_CODE = 0;	
	private Activity currentActivity;	
	private TextToSpeech tts;
	
	public static void init(Activity activity)
	{
		instance = new SpeakHelper();
		
		instance.currentActivity = activity;
        Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		instance.currentActivity.startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);	
	}
		
	public void speak(String text)
	{
		if (text == null || text.length() == 0) {
			return;
		}
		
		Toast.makeText(currentActivity, "Saying: " + text, Toast.LENGTH_LONG).show();
		tts.speak(text, TextToSpeech.QUEUE_ADD, null);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				tts = new TextToSpeech(currentActivity, this);
			} 
			else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				currentActivity.startActivity(installIntent);
			}
		}	
	}	

	public void onInit(int status) {		
		if (status == TextToSpeech.SUCCESS) {
			Toast.makeText(currentActivity, 
					"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
		}
		else if (status == TextToSpeech.ERROR) {
			Toast.makeText(currentActivity, 
					"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
		}
	}	
}
